import React, { useState, useEffect } from "react";
import { View, StyleSheet, Dimensions, Text, Image, TouchableOpacity } from "react-native";
import { Divider } from "@rneui/themed";
import LinearGradinet from 'react-native-linear-gradient';
import { useSelector, useDispatch } from "react-redux";
import IconNavBar from '@/components/IconNavBar'
import Loading from "@/components/LoadingModal";
import { sectokenCommonCenterProps } from '@/config/navigatorProps'
import { PayWithArray } from '@/config/config'
import { getValue } from '@/utils/deviceStorage'
import { AESdecrypt, getTransactionAmount } from '@/utils/util'
import { getFeeData, ethSafeSign1_1, getTransactionReceipt, ethSafeSign2_2, ethSafeReject2_2, ethSafeReject1_1 } from '@/utils/safe-transfer'
import RightImg from '@/assets/safe/right.png'
import { getETHBalance } from "@/utils/transfer";
import LockScreenEnter from '@/components/LockScreenEnter'
import CommonContext from '@/utils/createContext'

const { width, scale } = Dimensions.get('window')
const ratio = width * scale / 1080

const SectokenSendExecute = (props) => {

    const dispatch = useDispatch()
    const [loadingVisible, setLoadingVisible] = useState(false)
    const [coinType, setCoinType] = useState('')
    const [amountData, setAmountData] = useState({});
    const [isRejection, setIsRejection] = useState(false);
    const [modalVisible, setModalVisible] = useState(false);
    const feeData = useSelector((state) => state.sectokenSafeReducer.feeData || {});
    const selectedSafeWallet = useSelector((state) => state.sectokenMainReducer.selectedSafeWallet || {});
    const selectedPayWith = useSelector((state) => state.sectokenSafeReducer.selectedPayWith || {});
    const transcationDetail = useSelector((state) => state.sectokenMainReducer.transcationDetail || {});

    useEffect(() => {
        let params = props.route.params
        let re
        if (params && params.source === 'rejection') {
            re = true
            setIsRejection(true)
        }
        if (transcationDetail && transcationDetail.txId) {
            setLoadingVisible(true)
            setTimeout(() => {
                getPageData(re).then(() => setLoadingVisible(false))
                    .catch(() => setLoadingVisible(false))
            }, 100);
        }
    }, [transcationDetail])

    const getPageData = async (re) => {
        if (!re) {
            //获取交易金额信息
            let amountData = getTransactionAmount(transcationDetail.txInfo)
            amountData.logoUri = amountData.logoUri?.replace('/media/https%3A', 'https:/')
            setAmountData(amountData)
        }
        let obj = getValue('selectedWallet')
        let str = getValue('coinType')
        setCoinType(str)
        if (obj && obj.address) {
            let res = await getFeeData(obj.address, [obj.address], 1)
            dispatch({ type: "setFeeData", value: res || [] });
        }
        let list = getValue('walletList')
        if (list && list.length > 0) {
            for (let i = 0; i < list.length; i++) {
                let profileImg = Object.keys(PayWithArray)[Math.floor(Math.random() * 3)]
                let balance = await getETHBalance(list[i].address)
                list[i].value = balance
                list[i].profileImg = profileImg
            }
            dispatch({ type: "setSelectedPayWith", value: list[0] || {} });
            dispatch({ type: "setPayWithList", value: list || [] });
        }
    }

    const handlePressLeft = () => {
        props.navigation.goBack()
    }

    const handlePressPayWith = () => {
        props.navigation.navigate('safe-create-pay-with')
    }

    const handlePressNetFee = () => {
        props.navigation.navigate('safe-create-net-fee')
    }

    const handlePressSubmit = () => {
        setModalVisible(true)
    }

    const handleClose = () => {
        setModalVisible(false)
        if (transcationDetail && transcationDetail.txId && selectedPayWith && parseFloat(selectedPayWith.value) > 0) {
            setLoadingVisible(true)
            setTimeout(async () => {
                let pwd = getValue('lockPwd')
                let encryptStr = getValue('mnemonicStr')
                let decryptStr = AESdecrypt(pwd.substring(0, 16), pwd.substring(16), encryptStr)
                let obj = JSON.parse(JSON.stringify(feeData))
                let gaslimit = parseInt(parseInt(obj.gasConsume?.hex) * 1.3)
                obj.gasConsume = {
                    "type": "BigNumber",
                    "hex": "0x" + gaslimit.toString(16)
                }
                let txHash
                //交易的execute，执行完后跳转页面            
                if (transcationDetail.detailedExecutionInfo?.confirmationsRequired == 1) {
                    //1-1合约钱包或2-1合约钱包
                    if (isRejection) {
                        //rejection
                        txHash = await ethSafeReject1_1(transcationDetail, decryptStr, obj)
                    } else {
                        //confirmation
                        txHash = await ethSafeSign1_1(transcationDetail, decryptStr, obj)
                    }
                } else if (transcationDetail.detailedExecutionInfo?.confirmationsRequired == 2) {
                    //2-2合约钱包
                    if (isRejection) {
                        //rejection
                        txHash = await ethSafeReject2_2(transcationDetail, str, obj)
                    } else {
                        //confirmation
                        txHash = await ethSafeSign2_2(transcationDetail, str, obj)
                    }
                }
                var t = setInterval(async () => {
                    const tx = await getTransactionReceipt(txHash)
                    if (tx) {
                        clearInterval(t)
                        setLoadingVisible(false)
                        props.navigation.navigate({
                            name: 'safe-send-result',
                            params: {
                                source: 'send-execute',
                                txId: transcationDetail.txId,
                                isRejection
                            }
                        })
                    }
                }, 3000)
            }, 100);
        }
    }

    return (
        <View style={styles.container}>
            <IconNavBar {...props} {...sectokenCommonCenterProps} {...{ title: 'Execute' }} handlePressLeft={handlePressLeft} />
            <View style={styles.bodyContent}>
                {!isRejection && <View>
                    <View style={{ alignItems: 'center' }}>
                        <View style={{ ...styles.content1, justifyContent: 'space-between' }}>
                            <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                                <View style={styles.divider}></View>
                                <Image source={{ uri: amountData.logoUri }} style={styles.img1} />
                            </View>
                            <Text style={{ ...styles.title1, marginRight: 22 * ratio }}>{amountData.amountWithSymbol}</Text>
                        </View>
                    </View>
                    <Text style={{ ...styles.title2, marginLeft: 15 * ratio, marginTop: 14 * ratio }}>From</Text>
                    <View style={{ alignItems: 'center', marginTop: 12 * ratio }}>
                        <View style={styles.content2}>
                            <Image source={PayWithArray[selectedSafeWallet.profileImg]} style={styles.img2} />
                            <View style={{ marginLeft: 14 * ratio }}>
                                <Text style={styles.title1}>{selectedSafeWallet.label}</Text>
                                <Text style={{ ...styles.title2, width: 178 * ratio }}
                                    numberOfLines={1}
                                    ellipsizeMode='middle'>
                                    {selectedSafeWallet.address}
                                </Text>
                            </View>
                        </View>
                    </View>
                    <Text style={{ ...styles.title2, marginLeft: 15 * ratio, marginTop: 18 * ratio }}>To</Text>
                    <View style={{ alignItems: 'center', marginTop: 12 * ratio }}>
                        <View style={styles.content2}>
                            <Image source={PayWithArray['profile_logo2']} style={styles.img2} />
                            <View style={{ marginLeft: 14 * ratio }}>
                                {/* <Text style={styles.title1}>{sendData.toAddress.label}</Text> */}
                                <Text style={{ ...styles.title2, width: 178 * ratio }}
                                    numberOfLines={1}
                                    ellipsizeMode='middle'>
                                    {transcationDetail.txInfo?.direction === 'OUTGOING' ? transcationDetail.txInfo?.recipient?.value : transcationDetail.txInfo?.sender?.value}
                                </Text>
                            </View>
                        </View>
                    </View>
                </View>}
                {isRejection && <Text style={{ ...styles.title3, width: 292 * ratio, marginLeft: 34 * ratio, textAlign: 'center' }}>
                    This is an on-chain rejection that doesn't send any funds.
                    Executing this on-chain rejection will replace all currently
                    awaiting transactions with nonce {transcationDetail.detailedExecutionInfo?.nonce}.
                </Text>}
                <View style={{ height: 104 * ratio, backgroundColor: '#F7F7F7', marginTop: 25 * ratio, width: 330 * ratio, marginLeft: 15 * ratio }}>
                    <TouchableOpacity onPress={handlePressPayWith}>
                        <View style={{ height: 51 * ratio, flexDirection: 'row', alignItems: 'center' }}>
                            <View style={{ flex: 5 }}>
                                <Text style={{ ...styles.title1, marginLeft: 15 * ratio }}>
                                    Pay with
                                </Text>
                            </View>
                            <View style={{ flex: 5, flexDirection: 'row', justifyContent: 'flex-end', alignItems: 'center' }}>
                                <Image source={PayWithArray[selectedPayWith.profileImg]} style={{ ...styles.img3, marginRight: 15 * ratio }} />
                                <View style={{ marginRight: 17 * ratio }}>
                                    <Text style={styles.title3}>{selectedPayWith.wallet_name}</Text>
                                    <Text style={styles.title4}>{selectedPayWith.value?.substring(0, 9)}{coinType}</Text>
                                </View>
                                <Image source={RightImg} style={{ ...styles.img4, marginRight: 15 * ratio }} />
                            </View>
                        </View>
                    </TouchableOpacity>
                    <Divider color="#EAEAEA" />
                    <TouchableOpacity onPress={handlePressNetFee}>
                        <View style={{ height: 51 * ratio, flexDirection: 'row', alignItems: 'center' }}>
                            <View style={{ flex: 5 }}>
                                <Text style={{ ...styles.title1, marginLeft: 15 * ratio }}>
                                    Network fee
                                </Text>
                            </View>
                            <View style={{ flex: 5, flexDirection: 'row', justifyContent: 'flex-end', alignItems: 'center' }}>
                                <Text style={{ ...styles.title1, marginRight: 15 * ratio }}>
                                    {feeData.totalFee?.substring(0, 9)} {coinType}
                                </Text>
                                <Image source={RightImg} style={{ ...styles.img4, marginRight: 15 * ratio }} />
                            </View>
                        </View>
                    </TouchableOpacity>
                </View>
                <View style={{ flex: 1, justifyContent: 'flex-end', alignItems: 'center', marginBottom: 24 * ratio }}>
                    <TouchableOpacity onPress={handlePressSubmit}>
                        <LinearGradinet colors={['#0EBBF8', '#0069F6']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={styles.button}>
                            <Text style={{ ...styles.title1, color: '#FFFFFF', textAlign: 'center' }}>Submit</Text>
                        </LinearGradinet>
                    </TouchableOpacity>
                </View>
            </View>
            {modalVisible && <CommonContext.Provider value={{ modalVisible, setModalVisible, handleClose }}>
                <LockScreenEnter {...props} />
            </CommonContext.Provider>}
            {loadingVisible && <Loading visible={loadingVisible} />}
        </View>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#FFFFFF'
    },
    bodyContent: {
        flex: 1,
        marginTop: 10 * ratio
    },
    content1: {
        width: 330 * ratio,
        height: 56 * ratio,
        backgroundColor: '#F7F7F7',
        flexDirection: 'row',
        alignItems: 'center'
    },
    content2: {
        width: 330 * ratio,
        height: 40 * ratio,
        flexDirection: 'row',
        alignItems: 'center'
    },
    divider: {
        width: 3 * ratio,
        height: 21 * ratio,
        backgroundColor: '#0A6EEB',
        marginLeft: 8 * ratio
    },
    img1: {
        width: 25 * ratio,
        height: 25 * ratio,
        marginLeft: 8 * ratio
    },
    img2: {
        width: 40 * ratio,
        height: 40 * ratio
    },
    img3: {
        width: 22 * ratio,
        height: 22 * ratio
    },
    img4: {
        width: 5 * ratio,
        height: 9 * ratio
    },
    title1: {
        fontSize: 16,
        fontFamily: 'SourceHanSansCN-Medium, SourceHanSansCN',
        fontWeight: '500',
        color: '#2C2C2C',
        lineHeight: 24
    },
    title2: {
        fontSize: 12,
        fontFamily: 'SourceHanSansCN-Medium, SourceHanSansCN',
        fontWeight: '500',
        color: '#606060',
        lineHeight: 18
    },
    title3: {
        fontSize: 14,
        fontFamily: 'SourceHanSansCN-Medium, SourceHanSansCN',
        fontWeight: '500',
        lineHeight: 21,
        color: '#2C2C2C'
    },
    title4: {
        fontSize: 11,
        fontFamily: 'SourceHanSansCN-Medium, SourceHanSansCN',
        fontWeight: '500',
        lineHeight: 17
    },
    button: {
        width: 320 * ratio,
        height: 50,
        borderRadius: 28,
        justifyContent: 'center'
    }
})
export default SectokenSendExecute
